<?php

namespace p5\objects;

/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/5/7
 * Time: 20:26
 */
class FixSizeList
{
    private $list = [];
    private $maxSize = 100;
    private $beginIndex = 0;

    public function __constrct($size = 100)
    {
        $this->maxSize = $size;
    }

    public function push($object)
    {
        if ($this->size() < $this->maxSize) {
            array_push($this->list, $object);
        } else {
            $this->list[$this->beginIndex] = $object;
            $this->beginIndex = ($this->beginIndex + 1) % $this->maxSize;
        }
    }

    public function get($index)
    {
        while (true) {
            if ($index >= 0) {
                break;
            }
            $index = $index + $this->size();
        }
        $index = ($index + $this->beginIndex) % $this->maxSize;
        if ($index >= $this->size()) {
            return null;
        }
        return $this->list[$index];
    }

    public function all()
    {
        return $this->list;
    }

    public function last()
    {
        return $this->get($this->size() - 1);
    }

    public function size()
    {
        return count($this->list);
    }
}